package com.example.fiction.base;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.fiction.interfacz.IDirectory;

import java.util.ArrayList;
import java.util.List;

/**
 * create:2019/3/22 22:46
 * author: 姚鸿杰
 **/
public class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewAdapter<T>.BaseHolder> {

    private Context context;
    private LayoutInflater layoutInflater;
    private int layoutId;
    private int variableId;
    private List<T> lists;
    private IDirectory<T> iDirectory;

    public void setItemClickListener(IDirectory<T> iDirectory) {
        this.iDirectory = iDirectory;
    }

    public BaseRecyclerViewAdapter(Context context, LayoutInflater layoutInflater,
                                   int layoutId, int variableId, List<T> lists) {
        this.context = context;
        this.layoutInflater = layoutInflater;
        this.layoutId = layoutId;
        this.variableId = variableId;
        if (lists != null)
            this.lists = lists;
        else
            this.lists = new ArrayList<>();
    }

    public void setLists(List<T> lists) {
        if (lists != null)
            this.lists = lists;
        else
            this.lists = new ArrayList<>();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BaseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewDataBinding viewDataBinding = DataBindingUtil.inflate(layoutInflater, layoutId, parent, false);
        BaseHolder baseHolder = new BaseHolder(viewDataBinding.getRoot().getRootView());
        baseHolder.setBinding(viewDataBinding);
        return baseHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BaseHolder baseHolder, final int position) {
        baseHolder.setContent(lists.get(position));
        baseHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iDirectory.itemClick(v, position, lists.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        return this.lists.size();
    }

    public class BaseHolder extends RecyclerView.ViewHolder {

        private ViewDataBinding binding;

        public BaseHolder(@NonNull View itemView) {
            super(itemView);
        }

        public void setContent(T t) {
            this.binding.setVariable(variableId, t);
            this.binding.executePendingBindings();
        }

        public void setBinding(ViewDataBinding binding) {
            this.binding = binding;
        }

        public ViewDataBinding getBinding() {
            return this.binding;
        }
    }
}
